package com.eairlv.share.auto.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eairlv.share.auto.entity.Result;
import com.eairlv.share.auto.entity.po.ShareTableRecordPO;
import com.eairlv.share.auto.entity.vo.ShareTableRecordVO;
import com.eairlv.share.auto.mapper.ShareTableRecordMapper;
import com.eairlv.share.auto.utils.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author eairlv
 * @description
 * @date 11:23 2020/1/16
 */
@Slf4j
@Service
public class ShareTableRecordService {

    @Autowired
    ShareTableRecordMapper shareTableRecordMapper;

    /**
     * 查询分片执行记录
     * @param id
     * @return
     */
    public Result<List<ShareTableRecordVO>> record(Integer id) {
        return Result.ok(getRecordByShareTableId(id)
                .parallelStream()
                .map(e -> BeanUtil.copyProperties(e, ShareTableRecordVO.class))
                .collect(Collectors.toList()));
    }

    /**
     * 插入分片执行记录
     * @param shareTableRecordPO
     * @return
     */
    public Integer insert(ShareTableRecordPO shareTableRecordPO){
        shareTableRecordMapper.insert(shareTableRecordPO);
        return shareTableRecordPO.getId();
    }

    /**
     * 通过shareTableId查询执行记录
     * @param shareTableId
     * @return
     */
    public List<ShareTableRecordPO> getRecordByShareTableId(Integer shareTableId){
        QueryWrapper<ShareTableRecordPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("share_table_id", shareTableId);
        queryWrapper.orderByDesc("create_time");
        return shareTableRecordMapper.selectList(queryWrapper);
    }
}
